import cgi, logging
from model import *
from manage import ManageHandler
from record import TableRecord
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import datetime
from django.utils import simplejson
from google.appengine.ext.webapp.util import login_required

import os, StringIO, csv, datetime
from google.appengine.ext.webapp import template

#data models

    



from google.appengine.api import mail


def email_notify(pm, message):
    p = ListTable.all().filter('value =', pm).filter('list_name =', 'pm').fetch(1)
    if p:
        email_address = '' #p.value2
        if email_address=='':
            msg = '%s does not provide an email' % pm
            email_address = 'ymeng@dlz.com'

            
    else:
        email_address = 'ymeng@dlz.com'
        msg = '%s could not be found in the address book.' % pm
    mail.send_mail(sender=users.get_current_user().email(),
              to=email_address,
              subject="Your Project Impact Record was updated",
              body=message + '\n' + msg)
    logging.info('Email is sent to %s : %s' % (pm, message + '\n' + msg))

class HelpPage(webapp.RequestHandler):
    """the root of the webapp  """
    @login_required
    def get(self):
        if users.get_current_user():
             values = {}
             path = os.path.join(os.path.dirname(__file__), 'help.htm')
             self.response.out.write(template.render(path, values))
        
class MainPage(webapp.RequestHandler):
    """the root of the webapp  """
    @login_required
    def get(self):
        if users.get_current_user():
             values = {
              'user': users.GetCurrentUser(),
              'admin_url': '/manage',
              'help_url': '/help',
              'logout_url': users.CreateLogoutURL('http://' + self.request.host + '/')
            }

             path = os.path.join(os.path.dirname(__file__), 'index.htm')
             self.response.out.write(template.render(path, values))
            
            
            

     

class ListHandler(webapp.RequestHandler):
    def get(self):
        list_name = self.request.get('list_name')
        q = ListTable.all().filter('list_name =', list_name).order('value')
        results = []
        for r in q:
            results.append({'value': r.value})
        self.response.headers["Content-Type"] = "application/json"
        self.response.out.write(simplejson.dumps({'results': results, 'totalCount': len(results)}))
        
                    
class ImpactHandler(webapp.RequestHandler):
    def getimpact(self):
        """get a list of impact"""
        direction = self.request.get('dir')
        limit = self.request.get('limit')
        offset = self.request.get('start')
        record_status = self.request.get('record_status')#delete or not
        review_status = self.request.get('review_status')#internal or not
        if limit=='':
            limit = 10
        if offset=='':
            offset = 0
        
        sort = self.request.get('sort')
        query = Impact().all()
        if direction=='DESC':
            sort = '-' + sort
            
        results = []
        q = query.order(sort).order('pm')
        if record_status:
            q.filter('record_status = ', record_status)
        if review_status:
            q.filter('reviewstatus = ', review_status)
        for i in q.fetch(int(limit), int(offset)):
            result = {}
            for fld in i.fields().keys():
                v = getattr(i, fld)
                if isinstance(v, datetime.datetime):
                    v = '%02d/%02d/%04d' % (v.month, v.day, v.year)
                if fld=='user':
                    v = v.nickname()
                result[fld] = v
            
            result['projectid'] = str(i.key())
            results.append(result)
        self.response.headers["Content-Type"] = "application/json"
        self.response.out.write(simplejson.dumps({'results': results, 'totalCount': query.count(), 'success': True}))

        
    def get(self):
        if users.get_current_user():
            self.getimpact()
        else:
            self.response.headers["Content-Type"] = "application/json"
            self.response.out.write(simplejson.dumps({'results': [], 'totalCount': 0, 'success': False, 'msg': 'login required'}))
            return
    
    def delete(self):
        """delete a record"""
        if not users.get_current_user():
            self.response.headers["Content-Type"] = "application/json"
            self.response.out.write(simplejson.dumps({'results': [], 'totalCount': 0, 'success': False, 'msg': 'login required'}))
            return
        keyvalue = self.request.get('projectid')
        
        r =  TableRecord(keyvalue, Impact.fields().keys())
        email_notify(r['pm'], 'project %s is deleted' % r['project'])
        r.delete()
        if r.exists:
            r.delete()
            status = True
            msg = 'Reord is successfully deleted.'
        else:
            status = False
            msg = 'No record found.'
        self.response.headers["Content-Type"] = "application/json"
        self.response.out.write(simplejson.dumps({'msg': msg, 'success': status}))
        
        
    
    def post(self):
        rtype = self.request.get('request_type')
        
        if rtype=='list':
            self.getimpact()
            return
        elif rtype =='delete':
            self.delete()
        elif rtype=='new':
            if self.request.get('projectid')=='': 
                rtype = 'new'
            else:
                rtype = 'update'
            if rtype=='new':
                k = None
                msg = 'record is created'
            elif rtype=='update':
                k = self.request.get('projectid')
                msg = 'record is updated'
            
            i = TableRecord(k, Impact.fields().keys(), ['ctime', 'mtime', 'user'])
            
            if i:
                pass
            else:
                self.response.headers["Content-Type"] = "application/json"
                self.response.out.write(simplejson.dumps({'msg': 'Record not found.', 'success': False}))
            
            
            for fld in Impact.fields().keys():
                if fld in ['x', 'y']:
                    try:
                        i[fld] = float('%.6f' % float(self.request.get(fld)))
                    except:
                        i[fld] = -1.0
                elif fld in ['roadway', 'garage', 'adaparking', 'sidewalk']:
                    v = self.request.get(fld, default_value=False)
                    if v:
                        v = True
                    i[fld] = v
                elif fld in ['start_date', 'end_date']:
                    v = self.request.get(fld)
                    m, d, y = v.split('/')
                    i[fld] = datetime.datetime(int(y), int(m), int(d))
                else:
                    if fld in i.fields and not fld in i.protected_fields:
                        i[fld] = self.request.get(fld)
            #need to check record status
            i['record_status'] = 'existing'
            if rtype=='new':
                i.insert(Impact)
                email_notify(i['pm'], 'project %s is created' % i['project'])
            elif rtype=='update':
                i.save_changes()
                email_notify(i['pm'], 'project %s is updated' % i['project'])
            self.response.headers["Content-Type"] = "application/json"
            self.response.out.write(simplejson.dumps({'msg': msg, 'success': True}))

                

        
application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/manage', ManageHandler),
                                      ('/help', HelpPage),
                                      ('/list', ListHandler),
                                      ('/test', ImpactHandler)],
                                     debug=True)




def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
